import logging
import json


class RequestLoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        # 在请求处理之后，将请求体日志添加到日志记录中
        self.log_request_body(request)

        return response

    def log_request_body(self, request):
        # 在请求处理之前记录请求体
        request_body = request.body

        try:
            # 尝试解析请求体为 JSON
            json_body = json.loads(request_body)
            logging.info(f"Request body (JSON): {json_body}")
        except json.JSONDecodeError:
            if request_body.strip():
                # 请求体不是 JSON 格式
                logging.warning(f"Request body is not valid JSON: {request_body}")
            else:
                # 请求体为空
                logging.info("Request body is empty")
